<?php
namespace app\model\book;

use think\db\Query;
use think\facade\Db;
use think\Model;
class BookModel extends Model {

    protected $table = 'book';

    protected $field = '';

    protected $schema = [
        'id' => 'int',
        'title' => 'string',
        'author' => 'string',
        'cate_id' => 'int',
        'create_time' => 'timestamp',
    ];


    public function getList($where = [],$order = [],$limit = [0,5]) {

        /* JOIN写法, 用这种不如自己写, 自己写自由 */
//        $list = $this->hasWhere('cateInfo', function(Query $query) {
//            $query->where('name','=','文学');
//        })->with(['cateInfo' => function(Query $query) {
//            $query->field('id,name');
//        }])->where($where)->limit($limit[0],$limit[1])->select()->toArray();

        /* where in 方法查询效率高, 非关联查询 */

        $list = $this->with(['cateInfo' => function(Query $query) {
            $query->field('id,name');
        }])->where($where)->limit($limit[0],$limit[1])->select()->toArray();
        return $list;

    }

    /* 追加字段查询,循环查询,效率低 */
    public function getAppendList($where = [],$order = [],$limit = [0,5]) {
        $list = $this->where($where)->append(['cate_name'])->limit($limit[0],$limit[1])->select()->toArray();
        return $list;
    }

    /* 追加属性写法 */
    public function getCateNameAttr($value,$row) {
        return Db::table('book_cate')->where('id','=',$row['cate_id'])->value('name');
    }

    public function cateInfo() {
        return $this->hasOne(BookCateModel::class,'id','cate_id');
    }

}